package com.tim.app.ui.fragment.selceted;

import android.content.res.Configuration;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.application.library.base.BaseFragment;
import com.application.library.net.StringResponseCallback;
import com.application.library.runtime.event.EventListener;
import com.application.library.runtime.event.EventManager;
import com.application.library.widget.EmptyLayout;
import com.application.library.widget.loadmore.LoadMoreContainer;
import com.application.library.widget.loadmore.LoadMoreHandler;
import com.application.library.widget.loadmore.LoadMoreRecycleViewContainer;
import com.application.library.widget.recycle.BaseRecyclerAdapter;
import com.application.library.widget.recycle.WrapRecyclerView;
import com.google.gson.Gson;
import com.lzy.okhttputils.OkHttpUtils;
import com.tim.app.R;
import com.tim.app.constant.AppKey;
import com.tim.app.constant.EventTag;
import com.tim.app.server.api.API_User;
import com.tim.app.server.entry.Topic;
import com.tim.app.server.result.GoodAtTopicResult;
import com.tim.app.server.result.ResponseResult;
import com.tim.app.ui.activity.SearchTopicActivity;
import com.tim.app.ui.activity.selected.TopicDetailActivity;
import com.tim.app.ui.adapter.selceted.GoodAtTopicAdapter;
import com.tim.app.ui.popup.ActionPop;
import com.tim.app.util.ToastUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * 话题页面
 */
public class GoodAtTopicFragment extends BaseFragment implements View.OnClickListener, LoadMoreHandler, BaseRecyclerAdapter.OnItemClickListener, BaseRecyclerAdapter.OnItemLongClickListener {

    public static final String TAG = "GoodAtTopicFragment";
    private View rootView;

    private LoadMoreRecycleViewContainer load_more;
    private WrapRecyclerView wrvSubject;
    private GoodAtTopicAdapter adapter;
    private List<Topic> dataList;
    private EmptyLayout emptyLayout;

    private int pageNumber = 1;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (null == rootView) {
            rootView = inflater.inflate(R.layout.fragment_good_at_topic, container, false);
            rootView.findViewById(R.id.ivAddGoodAtTopic).setOnClickListener(this);
            rootView.findViewById(R.id.ibBack).setOnClickListener(this);

            load_more = (LoadMoreRecycleViewContainer) rootView.findViewById(R.id.load_more);
            wrvSubject = (WrapRecyclerView) rootView.findViewById(R.id.wrvSubject);

            wrvSubject.setOverScrollMode(View.OVER_SCROLL_NEVER);
            load_more.useDefaultFooter(View.GONE);
            load_more.setAutoLoadMore(true);
            load_more.setLoadMoreHandler(this);

            if (dataList == null) {
                dataList = new ArrayList<>();
            }
            LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
            layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            wrvSubject.setLayoutManager(layoutManager);

            emptyLayout = new EmptyLayout(getActivity(), load_more);
            emptyLayout.showLoading();
            emptyLayout.setEmptyButtonShow(false);
            emptyLayout.setEmptyText("你还没有添加擅长的话题", "");

            adapter = new GoodAtTopicAdapter(getActivity(), dataList, false);
            adapter.setOnItemClickListener(this);
            adapter.setOnItemLongClickListener(this);
            wrvSubject.setAdapter(adapter);
        }
        initData();
        EventManager.ins().registListener(EventTag.DO_DELETE, eventListener);
        return rootView;
    }

    EventListener eventListener = new EventListener() {
        @Override
        public void handleMessage(int what, int arg1, int arg2, Object dataobj) {
            switch (what) {
                case EventTag.DO_DELETE:
                    int position = (int) dataobj;
                    cancelGoodAt(position);
                    break;
            }
        }
    };

    /**
     * 取消擅长
     *
     * @param position
     */
    private void cancelGoodAt(final int position) {
        Topic topic = dataList.get(position);
        API_User.ins().cancelGoodAt(TAG, topic.getActionStateMsg().getAdeptTopic(), topic.getId(), AppKey.TYPE_GOOD_AT, new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                    dataList.remove(position);
                    adapter.notifyDataSetChanged();
                    if (dataList.size() == 0) {
                        emptyLayout.showEmpty();
                    }
                    ToastUtil.showToast("取消成功");
                } else {
                    ToastUtil.showToast(errMsg);
                }
                return false;
            }
        });
    }

    /**
     * 初始化数据
     */
    public void initData() {
        pageNumber = 1;
        API_User.ins().getGoodAtTopics(TAG, pageNumber, AppKey.PAGE_SIZE, refreshCallback);
    }

    StringResponseCallback refreshCallback = new StringResponseCallback() {
        @Override
        public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
            if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                GoodAtTopicResult result = new Gson().fromJson(resultValue, GoodAtTopicResult.class);
                if (null != result.getRes() && null != result.getRes().getArraylist()) {
                    dataList.clear();
                    if (null != result.getRes().getArraylist().getResult()) {
                        dataList.addAll(result.getRes().getArraylist().getResult());
                        adapter.notifyDataSetChanged();
                    }
                    if (dataList.size() == 0) {
                        emptyLayout.showEmpty();
                    } else {
                        emptyLayout.showContent();
                    }
                    pageNumber = result.getRes().getArraylist().getCurrentPageNo();
                    if (pageNumber != result.getRes().getArraylist().getTotalPageCount()) {
                        load_more.loadMoreFinish(false, true);
                    } else {
                        load_more.loadMoreFinish(false, false);
                    }
                }
            }
            return false;
        }
    };

    StringResponseCallback moreCallback = new StringResponseCallback() {
        @Override
        public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
            if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                GoodAtTopicResult result = new Gson().fromJson(resultValue, GoodAtTopicResult.class);
                if (null != result && null != result.getRes().getArraylist()) {
                    if (null != result.getRes().getArraylist().getResult()) {
                        dataList.addAll(result.getRes().getArraylist().getResult());
                        adapter.notifyDataSetChanged();
                    }
                    pageNumber = result.getRes().getArraylist().getCurrentPageNo();
                    if (pageNumber != result.getRes().getArraylist().getTotalPageCount()) {
                        load_more.loadMoreFinish(false, true);
                    } else {
                        load_more.loadMoreFinish(false, false);
                    }
                }
            }
            return false;
        }
    };

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onItemClick(View view, int position, long id) {
        Topic topic = dataList.get(position);
        TopicDetailActivity.start(getContext(), topic, false);
    }

    @Override
    public boolean onItemLongClick(View view, int position, long id) {
        ActionPop actionPop = new ActionPop(getActivity(), position);
        actionPop.show(wrvSubject);
        return false;
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (null != rootView && null != rootView.getParent()) {
            ((ViewGroup) rootView.getParent()).removeView(rootView);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventManager.ins().removeListener(EventTag.DO_DELETE, eventListener);
        OkHttpUtils.getInstance().cancelTag(GoodAtTopicAdapter.TAG);
        OkHttpUtils.getInstance().cancelTag(TAG);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ibBack:
                EventManager.ins().sendEvent(EventTag.GOTO_ANSWER, 0, 0, null);
                break;
            case R.id.ivAddGoodAtTopic:
                SearchTopicActivity.start(getContext());
                break;
            default:
                break;
        }
    }

    @Override
    public void onLoadMore(LoadMoreContainer loadMoreContainer) {
        API_User.ins().getGoodAtTopics(TAG, pageNumber + 1, AppKey.PAGE_SIZE, moreCallback);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }


}
